/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-21 08:39:50
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-22 14:09:36
 * @Description: 登录日志中间件
 */
import { Context } from "egg";
// import { sysLogInterface } from "../model/sys/log";

export default (options) => {
  return async (ctx: Context, next) => {
    // console.log(options);
    const startTime = Date.now();
    const params = {
      query: ctx.query,
      params: ctx.params,
      body: "",
    };

    // console.log("user will login");
    const logData = {
      type: 0,
      type_name: "login",
      user_id: 0,
      user_name: ctx.request.body.user_name,
      request_url: ctx.request.path,
      method: ctx.request.method,
      params: JSON.stringify(params),
      request_ip: ctx.request.ip,
      response_status: 0,
      result: "",
      app_status: "",
      user_agent: ctx.headers["user-agent"],
      time: 0,
    };

    // 如果是登出
    if (options && options.type === "logout") {
      logData.type_name = "logout";
      logData.user_id = ctx.loginUserInfo.uid as number;
      logData.user_name = ctx.loginUserInfo.name;
    }
    await next();
    logData.result = ctx.body.msg; //login 输出的信息中msg
    logData.response_status = ctx.status;
    logData.app_status = ctx.body.code;
    logData.time = Date.now() - startTime;
    // console.log(logData);
    // console.log(ctx.headers);
    // 写入数据库日志
    ctx.model.Sys.Log.create(logData);
  };
};
